#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
打包脚本 - 将find_duplicate_files.py打包为可执行文件
"""

import os
import subprocess
import sys
import platform

def check_pyinstaller():
    """检查是否已安装PyInstaller"""
    try:
        subprocess.run([sys.executable, "-m", "pip", "show", "pyinstaller"], 
                      stdout=subprocess.PIPE, 
                      stderr=subprocess.PIPE, 
                      check=True)
        return True
    except subprocess.CalledProcessError:
        return False

def install_pyinstaller():
    """安装PyInstaller"""
    print("正在安装PyInstaller...")
    try:
        subprocess.run([sys.executable, "-m", "pip", "install", "pyinstaller"], 
                      check=True)
        print("PyInstaller安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"安装PyInstaller失败: {e}")
        return False

def build_executable():
    """构建可执行文件"""
    print("正在构建可执行文件...")
    
    # 根据操作系统确定打包选项
    system = platform.system()
    if system == "Windows":
        icon_option = ["--icon=file_icon.ico"] if os.path.exists("file_icon.ico") else []
    elif system == "Darwin":  # macOS
        icon_option = ["--icon=file_icon.icns"] if os.path.exists("file_icon.icns") else []
    else:  # Linux
        icon_option = []
    
    try:
        # 构建命令
        command = [
            sys.executable, 
            "-m", 
            "PyInstaller", 
            "--onefile",  # 单文件模式
            "--windowed",  # 不显示控制台窗口
            "--name", "查找重复文件",  # 可执行文件名称
            *icon_option,
            "find_duplicate_files.py"
        ]
        
        # 执行打包命令
        subprocess.run(command, check=True)
        
        # 打包成功，提示用户
        if system == "Windows":
            exe_path = os.path.abspath(os.path.join("dist", "查找重复文件.exe"))
        elif system == "Darwin":
            exe_path = os.path.abspath(os.path.join("dist", "查找重复文件.app"))
        else:
            exe_path = os.path.abspath(os.path.join("dist", "查找重复文件"))
        
        print("\n打包成功！")
        print(f"可执行文件位置: {exe_path}")
        
        return True
    except subprocess.CalledProcessError as e:
        print(f"构建可执行文件失败: {e}")
        return False

def main():
    """主函数"""
    print("=== 查找重复文件工具打包程序 ===\n")
    
    # 检查是否已安装PyInstaller
    if not check_pyinstaller():
        print("未检测到PyInstaller，需要先安装")
        if not install_pyinstaller():
            print("无法安装PyInstaller，打包终止")
            return False
    
    # 构建可执行文件
    if build_executable():
        print("\n打包过程已完成，您可以分发dist目录中的可执行文件。")
    else:
        print("\n打包过程失败，请检查错误信息。")

if __name__ == "__main__":
    main()
    input("\n按Enter键退出...") 